package com.laker.admin.module.sys.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.laker.admin.framework.aop.trace.EasyTrace;
import com.laker.admin.framework.aop.trace.SpanType;
import com.laker.admin.framework.aop.trace.TraceCodeBlock;
import com.laker.admin.framework.ext.mybatis.UserDataPower;
import com.laker.admin.module.sys.entity.SysDept;
import com.laker.admin.module.sys.entity.SysUser;
import com.laker.admin.module.sys.mapper.SysDeptMapper;
import com.laker.admin.module.sys.mapper.SysUserMapper;
import com.laker.admin.module.sys.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author laker
 * @since 2021-08-05
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    @Autowired
    SysDeptMapper deptMapper;

    @EasyTrace(spanType = SpanType.Service)
    @Override
    public SysUser getUserAndDeptById(Long userId) {
        SysUser user = this.getById(userId);
        if (user == null) {
            return null;
        }
        TraceCodeBlock.trace("deptMapper.selectById", value -> user.setDept(deptMapper.selectById(user.getDeptId())));
        return user;
    }

    @Override
    public List<UserDataPower> getUserDataPowers(Long userId) {
        return TraceCodeBlock.trace("sysUserMapper.getUserDataPowers", () -> this.getBaseMapper().getUserDataPowers(userId));
    }

    /**
     * 获取当前部门及其子部门id
     * @param deptId 部门 ID
     * @return {@link Set }<{@link Long }>
     */
    @Override
    public Set<Long> getSelfDeptIds(Long deptId) {
        Set<Long> deptIds = new HashSet<>();
        deptIds.add(deptId);
        List<SysDept> sysDepts = deptMapper.selectList(Wrappers.lambdaQuery(SysDept.class).eq(SysDept::getPid, deptId));
        while (!sysDepts.isEmpty()) {
            Set<Long> collect = sysDepts.stream().map(SysDept::getDeptId).collect(Collectors.toSet());
            sysDepts = deptMapper.selectList(Wrappers.lambdaQuery(SysDept.class).select(SysDept::getPid).in(SysDept::getPid, collect));
            deptIds.addAll(collect);
        }
        return deptIds;
    }

}
